/*
 * helperfuncs.c
 * CS 3251 Programming Assignment #2
 * Dustin Shiflett
 */ 

#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for gethostbyname(), socket(), connect(), sendto(), and recvfrom() */

#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() and alarm() */

#include <signal.h>     /* for sigaction() */
#include <sys/types.h>
#include <netinet/in.h>
#include <io.h>
#include <sys\stat.h> 
#include <fcntl.h>

#include "dropper.h"
#include "helperfuncs.h"

int debug = 0;

void closeSocket(int sockID) {
    int rc;
    if(sockID < 0) {
        return;
    }
    rc = close(sockID);
    if(rc < 0) {
        printf("Error closing a socket. Exiting.\n")
        fflush(stdout);
        exit(1);
    }
    printf("Socket closed.\n");
}

void DieWithError(char *errorMessage)
{
    perror(errorMessage);
    fflush(stdout);
    exit(1);
}

int calcRTO(int origRTO, int RTT) {
    /*Calculate Smooth Round Trip Time (SRTT) using Exponentially Weighted Moving Average (EWMA)
        SRTT_i+1 = (1-a)*SRTT[i-1]+a*RTT ; a = 1/8
        RFC793 TCP sets timeout to be 2*SRTT
        */
    int newSRTT, origSRTT;
    
    origSRTT = origRTO / 2;
    
    newSRTT = ((1 - SRTTCONSTANT) * origSRTT) + (SRTTCONSTANT * RTT);
    
    return (newSRTT * 2);
}

long fileExists(char* fileName) {
    long file_size = -1;
    FILE* file;
    struct stat buffer;
    int status;
    
    if(file = fopen(fileName, "r")) {
        status = fstat(file, &buffer);
        if(status != 0) {
            printf("Error getting file size via fstat()!\n");
        } else {
            file_size = (long)buffer.st_size;
        }
        fclose(file);
    }
    return file_size;
}

